package udf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.Text;

/**
 * @author cxx
 * 自定义hive函数
 * @create 2020-02-16 21:51
 **/
public class Function extends GenericUDF {
    /**
     * 该方法用于函数初始化操作，并定义函数的返回值类型；
     * @param arguments
     * @return
     * @throws UDFArgumentException
     */
    public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
        if (arguments.length != 2) {
            throw new UDFArgumentException("The function ARRAY_CONTAINS accepts 2 arguments.");
        }
        return  PrimitiveObjectInspectorFactory.writableStringObjectInspector;
    }

    /**
     * 函数处理的核心方法，用途和UDF中的evaluate一样；
     * @param arguments
     * @return
     * @throws HiveException
     */
    public Object evaluate(DeferredObject[] arguments) throws HiveException {
        StringBuilder stringBuilder = new StringBuilder ();
        for (DeferredObject argument : arguments) {
            stringBuilder.append (argument.get ());
            stringBuilder.append ("****");
        }
        return new Text (stringBuilder.toString ());
    }

    /**
     * 显示函数的帮助信息
     * @param children
     */
    public String getDisplayString(String[] children) {
        assert (children.length == 2);
        return "myconcat(" + children[0] + ", " + children[1] + ")";
    }
}
